package com.xingfudazi.framework.config;

import com.xingfudazi.common.utils.uuid.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

// 参考：https://zhuanlan.zhihu.com/p/433261155
public class MdcTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> map = MDC.getCopyOfContextMap();
        return () -> {
            try {
                MDC.setContextMap(map);
                String traceId = MDC.get("TRACE_ID");
                if (StringUtils.isBlank(traceId)) {
                    traceId = IdUtils.fastSimpleUUID();
                    MDC.put("TRACE_ID", traceId);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}